package com.cqupt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cqupt.service.DemoService;
import com.cqupt.utils.APIUtils;
import com.cqupt.utils.DateUtils;
import com.cqupt.utils.PageUtils;
import com.cqupt.utils.TextUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class DemoServiceImpl implements DemoService {

    /**
     * 根据主机 id 和 主机名称获取利用率
     * @param hostId 主机 id
     * @param name  主机名
     * @return
     */
    @Override
    public List<Map<String, Object>> getUtilizationByName(String hostId, String name) {
        String token = APIUtils.getToken();
//        根据主机 id 和主机名获取监控项
        List<Map<String, Object>> itemList = getItemsByName(token, hostId, name);
        String itemId = itemList.get(0).get("itemid").toString();
//        获取监控项历史数据
        List<Map<String, Object>> historyDataList = getItemHistoryData(token, itemId, "clock", "DESC", 20);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        将时间添加到历史数据中
        for(Map<String, Object> historyData : historyDataList) {
            String clock = sdf.format(new Date(Long.valueOf(historyData.get("clock").toString()) * 1000L));
            historyData.put("clock", clock);
        }
        return historyDataList;
    }

    /**
     * 获取主机列表
     * @return
     */
    @Override
    public List<Map<String, Object>> getAllOnlineHost() {
        final String token = APIUtils.getToken();
        ArrayList<String> imp_str = new ArrayList<>();
        imp_str.add("available");
        imp_str.add("snmp_available");
        imp_str.add("status");
        imp_str.add("hostid");
        imp_str.add("host");
        imp_str.add("name");
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("filter", new HashMap<String, Object>(){{
                    put("monitored_hosts", true);
                }});
                put("output",imp_str);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        return resultList;
    }

    /**
     *
     * @description: 监控设备总表
     * @param:
     * @return:
     * @author:
     * @time:
     */
    public List<Map<String, Object>> getHostList() {
        final String token = APIUtils.getToken();
//        获得主机详细信息列表
        List<Map<String, Object>> resultList = getAllOnlineHost();
        final List<String> hostIds = new ArrayList<>();
//        组装主机id数组 ids
        for (Map<String, Object> maps : resultList) {
            hostIds.add((String) maps.get("hostid"));
        }
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "hostinterface.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
               put("output","extend");
               put("hostids",hostIds);
            }});
        }};
//        获取主机接口信息列表
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> result = (List<Map<String, Object>>)responseMap.get("result");
        for (int i = 0; i < result.size(); i++){
            result.get(i).put("hostname",resultList.get(i).get("name"));
            result.get(i).put("status",resultList.get(i).get("status"));
        }
        return result;
    }

    /**
     * 通过主机 id 和名称获取监控项
     * @param token
     * @param hostId 主机 id
     * @param name  主机名
     * @return
     */
    public List<Map<String, Object>> getItemsByName(final String token, final String hostId, final String name) {
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", "extend");
                put("hostids", hostId);
                put("search", new HashMap<String, Object>(){{
                    put("name", name);
                }});
                put("sortfield", "name");
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        return resultList;
    }

    /**
     * 获取历史数据
     * @param token
     * @param itemId 主机 id
     * @param sortfield 分类领域
     * @param sortorder 分类顺序
     * @param limit 个数限制
     * @return
     */
    public List<Map<String, Object>> getItemHistoryData(final String token, final String itemId, final String sortfield, final String sortorder, final Integer limit) {
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "history.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", "extend");
                put("history", 0);
                put("itemids", itemId);
                put("sortfield", sortfield);
                put("sortorder", sortorder);
                put("limit", limit);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        return resultList;
    }

    /**
     * @see DemoService#getPageableOnlineHost(String, String)
     * 调用了同类的getAllOnlineHost()
     */
    @Override
    public Map<String, Object> getPageableOnlineHost(String curPage, String pageSize) {
        // 拿到API数据
        List<Map<String, Object>> allOnlineHost = getAllOnlineHost();
        // 记录总数据
        final int dataNum = allOnlineHost.size();
        // 分页
        List<Map<String, Object>> resList = PageUtils.getDataListByCurPage(allOnlineHost, curPage, pageSize);
        // 将消息list和总条数int封装到map
        Map<String, Object> resMap = TextUtils.packDataToMap(resList, dataNum);

        return resMap;
    }

//    // 查询服务器类型在线主机
//    public List<Map<String, Object>> getAllOnlineHost_agent() {
//        final String token = APIUtils.getToken();
//        ArrayList<String> imp_str = new ArrayList<>();
//        imp_str.add("available");
//        imp_str.add("snmp_available");
//        imp_str.add("status");
//        imp_str.add("hostid");
//        imp_str.add("host");
//        imp_str.add("name");
//        ArrayList<String> inters = new ArrayList<>();
//        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
//            put("jsonrpc", "2.0");
//            put("method", "host.get");
//            put("id", 1);
//            put("auth", token);
//            put("params", new HashMap<String, Object>(){{
//                put("filter", new HashMap<String, Object>(){{
//                    put("monitored_hosts", true);
//                    put("available","1");
//                    put("available","2");
//                }});
//                put("selectInterfaces",inters);
//                put("output",imp_str);
//            }});
//        }};
//        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
//        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
//        return resultList;
//    }


    /**
     *  查询 snmp 类型主机列表
     * @return
     */
    public List<Map<String, Object>> getAllOnlineHostid_snmp() {
        final String token = APIUtils.getToken();
        ArrayList<String> imp_str = new ArrayList<>();
        // 主机 id
        imp_str.add("hostid");
        // snmp 可用性
        imp_str.add("snmp_available");
        // 主机名称
        imp_str.add("host");
        // 主机状态
        imp_str.add("status");
        ArrayList<String> avail = new ArrayList<>();
        // 1为可用，2为不可用
        avail.add("1");
        avail.add("2");
        List<String> interfaces = new ArrayList<>();
        // ip 地址
        interfaces.add("ip");
        // 端口号
        interfaces.add("port");
        // 筛选需要的资产清单
        List<String> inv = new ArrayList<String>();
        inv.add("notes");
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("filter", new HashMap<String, Object>(){{
                    put("snmp_available",avail);
                }});
                put("searchByAny",true);
                put("output",imp_str);
                put("selectInterfaces",interfaces);
                put("selectInventory",inv);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        return resultList;
    }


    /**
     * 查询 agent 类型主机列表
     * @return
     */
    public List<Map<String, Object>> getAllOnlineHostid_agent() {
        final String token = APIUtils.getToken();
        List<String> imp_str = new ArrayList<>();
        imp_str.add("hostid");
        imp_str.add("available");
        imp_str.add("host");
        imp_str.add("status");
        List<String> avail = new ArrayList<>();
        avail.add("1");
        avail.add("2");
        List<String> interfaces = new ArrayList<>();
        interfaces.add("ip");
        interfaces.add("port");
        // 筛选需要的资产清单
        List<String> inv = new ArrayList<String>();
        inv.add("notes");
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("filter", new HashMap<String, Object>(){{
                    put("available",avail);
                }});
                put("searchByAny",true);
                put("output",imp_str);
                put("selectInterfaces",interfaces);
                put("selectInventory",inv);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        return resultList;
    }
}
